package com.yxp.offer;

/**
 * @author : yang.xp
 * @date : 2021/8/25 10:16
 * @description : 剑指 Offer 58 - I. 翻转单词顺序
 */
public class Problem58_1 {

    public static void main(String[] args) {
        Problem58_1 problem58_1 = new Problem58_1();
        System.out.println(problem58_1.reverseWords(" "));
    }

    // 理解错意思了 hello world ： dlrow olleh
//    public String reverseWords(String s) {
//        if (s == null || s.length() == 0) {
//            return "";
//        }
//        char[] chars = s.toCharArray();
//        int firstIndex = 0, lastIndex = chars.length - 1;
//        while (firstIndex < lastIndex) {
//            char temp = chars[lastIndex];
//            chars[lastIndex] = chars[firstIndex];
//            chars[firstIndex] = temp;
//            firstIndex++;
//            lastIndex--;
//        }
//        return new String(chars);
//    }

    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        String[] strings = s.split(" ");
        if (strings.length == 0) {
            return "";
        }
        int lastIndex = strings.length - 1;
        String result = "";
        while (lastIndex >= 0) {
            if (strings[lastIndex].length() > 0) {
                result += strings[lastIndex];
                result += " ";
            }
            lastIndex--;
        }
        return result.substring(0, result.length() - 1);
    }
}
